package springboot.demo.shiro.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springboot.demo.shiro.common.util.PasswordUtil;
import springboot.demo.shiro.entity.dto.QueryEmployeeDto;
import springboot.demo.shiro.entity.dto.ResultDto;
import springboot.demo.shiro.entity.po.Employee;
import springboot.demo.shiro.service.IEmployeeService;

/**
 * <p>Project: springboot-demo </p>
 * 
 * <p>Function:  </p>
 * 
 * <p>Description:  </p>
 * 
 * @author weiqiang.li
 * 
 * @date 2018/11/26
 * 
 * @version 1.0
 */
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @GetMapping("get/list")
    public ResultDto<?> getList(@RequestParam Integer pageSize, @RequestParam Integer pageNum) {
        IPage<Employee> page = employeeService.page(new Page<>(pageNum, pageSize),
                new QueryWrapper<Employee>());
        return ResultDto.builder().success(true).data(page.getRecords()).total(page.getTotal()).build();
    }

    @PostMapping("/search")
    public ResultDto<?> searchEmployee(@RequestBody QueryEmployeeDto queryEmployeeDto) {
        IPage<Employee> page = employeeService
                .page(new Page<Employee>(queryEmployeeDto.getPageNum(), queryEmployeeDto.getPageSize()),
                        new QueryWrapper<Employee>()
                                .eq("loginName", queryEmployeeDto.getLoginName()));
        return ResultDto.builder().success(true).data(page.getRecords()).total(page.getTotal()).build();
    }

    @PostMapping("/add")
    public ResultDto<?> addEmployee(@RequestBody Employee employee) {
        String salt = PasswordUtil.generateSalt();
        employee.setPasswordSalt(salt);
        employee.setPassword(PasswordUtil.encode(employee.getPassword(), employee.getPasswordSalt()));
        boolean result = employeeService.save(employee);
        return ResultDto.builder().success(result).build();
    }
}
